﻿using DataProcessor.DB.ORM;
using Hjt212Parser;
using log4net;
using System;
using System.Linq;

namespace DataProcessor.Processor
{
    public class StatusProcessor
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(StatusProcessor));

        public static void ProcessOnlineOffline(string content)
        {
            try
            {
                if (DataInstructionProcessor.HasQuestionOfPreprocess(content, out var info, out var dataTime, out var pollutantCodes, out var masterCode, out var pollutionInfo))
                {
                    return;
                }
                if(!dataTime.HasValue) return;

                using (var contextTarget = new PlatformEntities())
                {
                    var cn = Parser.GetStringByKey("CN", content);
                    switch (FactorTypeHelper.GetFactorType(content))
                    {
                        case EnumFactorType.Water:
                            //实时监控表（水）
                            var masterMonitorWater = contextTarget.RealDataMonitorMains
                                .FirstOrDefault(t => t.设备信息ID == info.ID);
                            if (masterMonitorWater == null)
                            {
                                masterMonitorWater = new RealDataMonitorMain();
                                masterMonitorWater.企业基本信息ID = info.企业基本信息ID;
                                masterMonitorWater.设备信息ID = info.ID;
                                masterMonitorWater.污染物类别ID = pollutionInfo.污染物类别ID;
                                contextTarget.RealDataMonitorMains.Add(masterMonitorWater);
                            }

                            masterMonitorWater.数采在离线状态时间 = dataTime;
                            masterMonitorWater.数采在线状态ID = cn.Contains("000") ? 802 : 801;
                            break;
                        case EnumFactorType.Gas:
                            //修改实时监控表（气）
                            var masterMonitorGas =
                                contextTarget.主实时监控气.FirstOrDefault(t => t.企业排口ID == info.ID);
                            if (masterMonitorGas == null)
                            {
                                masterMonitorGas = new 主实时监控气();
                                masterMonitorGas.企业基本信息ID = info.企业基本信息ID;
                                masterMonitorGas.企业排口ID = info.ID;
                                contextTarget.主实时监控气.Add(masterMonitorGas);
                            }
                            masterMonitorGas.在离线状态时间 = dataTime.Value;
                            masterMonitorGas.在线状态ID = cn.Contains("000") ? 802 : 801;

                            break;
                    }
                    contextTarget.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex + "->\n" + content);
            }
        }


    }
}
